package main

import (
	"context"
	"gitee.com/nanakura/h-scraper/internal/service"
	"github.com/wailsapp/wails/v2/pkg/runtime"
)

// App struct
type App struct {
	ctx context.Context
}

// NewApp creates a new App application struct
func NewApp() *App {
	return &App{}
}

// startup is called when the app starts. The context is saved
// so we can call the runtime methods
func (a *App) startup(ctx context.Context) {
	a.ctx = ctx
}

// CrawlAndDownload 根据网址和选择器爬取图片
func (a *App) CrawlAndDownload(url, selector string) (res []string) {
	if pics, err := service.DownloadPics(url, selector); err != nil {
		return
	} else {
		res = pics
	}
	return
}

func (a *App) CleanTmpCache() {
	service.CleanTmpDir()
}

func (a *App) GetSourceContent() (res []map[string]any) {
	res, err := service.GetSourcesContentHandler()
	if err != nil {
		println(err)
	}
	return
}

func (a *App) SetCurrentDocumentByUrl(url string) {
	err := service.SetCurrentDocument(url)
	if err != nil {
		println(err)
	}
}

func (a *App) GetTitleTable(url, urlSelector, textSelector string) []map[string]string {
	table, err := service.GetTitleTable(url, urlSelector, textSelector)
	if err != nil {
		println(err)
	}
	return table
}

func (a *App) GetContent(url, imgSelector, textSelector string) (res map[string]any) {
	content, err := service.GetContent(url, imgSelector, textSelector)
	if err != nil {
		println(err)
		return
	}
	res = content
	return
}

func (a *App) onBeforeClose(ctx context.Context) (prevent bool) {
	dialog, err := runtime.MessageDialog(ctx, runtime.MessageDialogOptions{
		Type:    runtime.QuestionDialog,
		Title:   "Quit?",
		Message: "Are you sure you want to quit?",
	})

	if err != nil {
		return false
	}
	return dialog != "Yes"
}
